package com.example.shortvideobackend.service;

import com.example.shortvideobackend.entity.Comment;
import com.example.shortvideobackend.entity.Video;
import com.example.shortvideobackend.entity.User;
import com.example.shortvideobackend.repository.CommentRepository;
import com.example.shortvideobackend.repository.VideoRepository;
import com.example.shortvideobackend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private VideoRepository videoRepository;

    @Autowired
    private UserRepository userRepository;

    public Comment addComment(Long videoId, Long userId, String content) {
        Video video = videoRepository.findById(videoId)
                .orElseThrow(() -> new RuntimeException("视频不存在"));
        
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        Comment comment = new Comment();
        comment.setVideo(video);
        comment.setUser(user);
        comment.setContent(content);
        
        return commentRepository.save(comment);
    }

    public List<Comment> getCommentsByVideoId(Long videoId) {
        return commentRepository.findByVideoIdOrderByCreatedAtDesc(videoId);
    }

    public void deleteComment(Long commentId, Long userId) {
        Comment comment = commentRepository.findById(commentId)
                .orElseThrow(() -> new RuntimeException("评论不存在"));

        // 只有评论作者或视频作者可以删除评论
        if (!comment.getUser().getId().equals(userId) && 
            !comment.getVideo().getUser().getId().equals(userId)) {
            throw new RuntimeException("无权删除此评论");
        }
        
        commentRepository.delete(comment);
    }

    public long getCommentCountForVideo(Long videoId) {
        return commentRepository.countByVideoId(videoId);
    }
} 